import { defineStore } from 'pinia'
import { info, login, logout, studentInfo } from '@/service/user'
import router from '@/router/index'
import {
  getToken,
  removeToken,
  setToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo
} from '@/utils/auth'
import { mode, modeType, loginTypes } from '@/utils/dicts'
import { userLogin } from '@/utils/types'

const loginType =
  mode === modeType.TEACHER
    ? loginTypes.channel_password
    : loginTypes.member_password

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: getUserInfo(),
    token: getToken()
  }),
  actions: {
    setInfo(info: any) {
      this.userInfo = info
      setUserInfo(info)
    },
    backLogin() {
      router.replace(`/${mode}`) // 返回登录页
    },
    /*清空用户信息*/
    clearUserInfo() {
      this.userInfo = {}
      this.token = ''
      removeToken()
      removeUserInfo()
    },
    /*用户登录*/
    async userLogin(ruleForm: userLogin) {
      const { data } = await login({ ...ruleForm, type: loginType })
      this.token = data.access_token
      setToken(this.token)
    },
    /*教师登录后获取直播间信息*/
    async getUserInfo() {
      const { data } = await info()
      this.setInfo(data)
    },
    /*获取学员信息*/
    async studentInfo() {
      const { data } = await studentInfo()
      data.userName = data.username
      data.avatarUrl = data.avatar_url
      delete data.username
      delete data.avatar_url
      this.setInfo(data)
    },

    /*退出登录*/
    async loginOut() {
      await logout({ type: loginType })
      this.clearUserInfo()
    }
  }
})
